739. 每日温度

739. 每日温度

Similar Question

Solution Tips

方案一: 单调栈

var dailyTemperatures = function(temperatures) {
    // 不懂单调栈是啥东西, 先来个暴力法呗.
    // 不用暴力法, 直接用栈, 记录一下 index 就完事了
    const stack = [[temperatures[0], 0]];
    const res = Array.from({length: temperatures.length});
    for (let i = 1; i < temperatures.length; i++) {
        while (temperatures[i] > stack[stack.length - 1]?.[0]) {
            // 循环出栈, 记录 index
            const [low, index] = stack.pop();
            res[index] = i - index;
        }
        // 入栈
        stack.push([temperatures[i], i]);
    }

    // 清空栈
    while (stack.length > 0) {
        const [val, index] = stack.pop();
        res[index] = 0;
    }

    return res;
};

其实不用记录 val ,直接记录 index 就可以了, 通过 temperatures[prevIndex] 可以获取到 val

pC7VQi9.png